package com.pro.addresslist.ui.activity;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.CharsetUtils;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.Toast;

import com.pro.addresslist.R;
import com.pro.addresslist.dal.model.ContactInfo;
import com.pro.addresslist.dal.model.ContactInfoBySqlite;
import com.pro.addresslist.tools.CameraInterface;
import com.pro.addresslist.tools.CameraInterface.CamOpenOverCallback;
import com.pro.addresslist.tools.DisplayUtil;
import com.pro.addresslist.tools.NetUtil;
import com.pro.addresslist.ui.common.BaseActivity;
import com.pro.addresslist.ui.view.CameraSurfaceView;
import com.pro.addresslist.ui.view.MaskView;

public class CameraActivity extends BaseActivity implements CamOpenOverCallback {
	private static final String TAG = "YanZi";
	CameraSurfaceView surfaceView = null;
	ImageButton shutterBtn;
	MaskView maskView = null;
	float previewRate = -1f;
	int DST_CENTER_RECT_WIDTH = 230; //230单位是dip
	int DST_CENTER_RECT_HEIGHT = 350;//350单位是dip
	Point rectPictureSize = null;

	private final String imgfilepath = Environment.getExternalStorageDirectory() + "/PlayCamera/camera.jpg";
	final File file = new File(imgfilepath); // 上传的待识别图片
	private final String key = "PLTWLWutf54FhJCBFxCReP"; // 用户ocrKey
	private final String secret = "b51c619d0d1043e9a6a926d27d7b4380"; // 用户ocrSecret
	private final String typeId = "20"; // 证件类型(例如:二代证正面为"2"。详见文档说明)
	private String format = "json"; //(返回的格式可以是xml，也可以是json)
	private final String url = "http://www.netocr.com/api/recog.do"; // http接口调用地址
	static String result = "";



	private void initUI(){
		surfaceView = (CameraSurfaceView)findViewById(R.id.camera_surfaceview);
		shutterBtn = (ImageButton)findViewById(R.id.btn_shutter);
		maskView = (MaskView)findViewById(R.id.view_mask);
	}
	private void initViewParams(){
		LayoutParams params = surfaceView.getLayoutParams();
		Point p = DisplayUtil.getScreenMetrics(this);
		params.width = p.x;
		params.height = p.y;
		Log.i(TAG, "screen: w = " + p.x + " y = " + p.y);
		previewRate = DisplayUtil.getScreenRate(this); //默认全屏的比例预览
		surfaceView.setLayoutParams(params);

		//手动设置拍照ImageButton的大小为120dip×120dip,原图片大小是64×64
		LayoutParams p2 = shutterBtn.getLayoutParams();
		p2.width = DisplayUtil.dip2px(this, 80);
		p2.height = DisplayUtil.dip2px(this, 80);;		
		shutterBtn.setLayoutParams(p2);	

	}

	@Override
	public void cameraHasOpened() {
		// TODO Auto-generated method stub
		SurfaceHolder holder = surfaceView.getSurfaceHolder();
		CameraInterface.getInstance().doStartPreview(holder, previewRate);
		if(maskView != null){
			Rect screenCenterRect = createCenterScreenRect(DisplayUtil.dip2px(this, DST_CENTER_RECT_WIDTH)
					,DisplayUtil.dip2px(this, DST_CENTER_RECT_HEIGHT));
			maskView.setCenterRect(screenCenterRect);
		}
	}
	private class BtnListeners implements OnClickListener{

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch(v.getId()){
			case R.id.btn_shutter:
				if(rectPictureSize == null){
					rectPictureSize = createCenterPictureRect(DisplayUtil.dip2px(CameraActivity.this, DST_CENTER_RECT_WIDTH)
							,DisplayUtil.dip2px(CameraActivity.this, DST_CENTER_RECT_HEIGHT));
				}
				CameraInterface.getInstance().doTakePicture(rectPictureSize.x, rectPictureSize.y,mContext);
				
				break;
			default:break;
			}
		}

	}
	
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 0:
				String result = (String) msg.obj;
				ContactInfo con=new ContactInfo();
				String ss="";
				try {
					JSONObject res=new JSONObject(result);
					if(res.getJSONObject("message").getInt("status")>=0){
						JSONArray jarray=res.getJSONArray("cardsinfo");
						JSONArray info=jarray.getJSONObject(0).getJSONArray("items");
						for(int i=0;i<info.length();i++){
							JSONObject coninfo=info.getJSONObject(i);
							if(coninfo.getString("nID").equals("0")){
								con.set_Name(coninfo.getString("content"));
								ss+="=="+coninfo.getString("content");
							}
							if(coninfo.getString("nID").equals("1")){
								con.set_Post(coninfo.getString("content"));
								ss+="=="+coninfo.getString("content");
							}
							if(coninfo.getString("nID").equals("2")){
								con.set_Mobile(coninfo.getString("content"));
								ss+="=="+coninfo.getString("content");
							}
							if(coninfo.getString("nID").equals("3")){
								con.set_Unit(coninfo.getString("content"));
								ss+="=="+coninfo.getString("content");
							}
							if(coninfo.getString("nID").equals("4")){
								con.set_DepartAddress(coninfo.getString("content"));
								ss+="=="+coninfo.getString("content");
							}
							if(coninfo.getString("nID").equals("5")){
								con.set_DepartTell(coninfo.getString("content"));
								ss+="=="+coninfo.getString("content");
							}
						}
					}
					else {
						Toast.makeText(getApplicationContext(),res.getJSONObject("message").getString("value"), Toast.LENGTH_LONG).show();
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					Toast.makeText(getApplicationContext(), "数据转换失败！", Toast.LENGTH_LONG).show();
					return;
				}
				disMissDialog();
				Intent i=new Intent(CameraActivity.this,NewContactsActivity.class);
			    i.putExtra("actions", "saomiao");
			    i.putExtra("saomiao", con);
			    startActivity(i);
			    finish();
				break;
			case 1:
				Toast.makeText(getApplicationContext(), (String) msg.obj, Toast.LENGTH_SHORT).show();
				break;
			}

		}
	};

	private class CardCast extends BroadcastReceiver{

		@Override
		public void onReceive(Context arg0, Intent intent) {
			if(intent.getAction().equals("camelDone")){
				if(!NetUtil.isNetworkAvailable(mContext)){
					Toast.makeText(getApplicationContext(), "请检查网络连接！", Toast.LENGTH_LONG).show();
					return;
				}
				// 判断目标文件是否存在
				if (!file.exists()) {
					Toast.makeText(getApplicationContext(), "图片文件不存在！", Toast.LENGTH_LONG).show();
					return;
				}
				showProgressDialog("正在识别中...");
				new Thread() {
					public void run() {
						String result = doPost(url, file, key, secret, typeId, format);
						Message mes = new Message();
						mes.obj = result;
						mes.what = 0;
						handler.sendMessage(mes);
					};
				}.start();
			}
		}
		
	}
	public final String doPost(String url, File file, String key, String secret, String typeId, String format) {
		String result = "";
		try {

			HttpClient client = new DefaultHttpClient(); // 1.创建httpclient对象
			HttpPost post = new HttpPost(url); // 2.通过url创建post方法

			if ("json".equalsIgnoreCase(format)) {
				post.setHeader("accept", "application/json");
			} else if ("xml".equalsIgnoreCase(format) || "".equalsIgnoreCase(format)) {
				post.setHeader("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
			}

			MultipartEntityBuilder builder = MultipartEntityBuilder.create(); // 实例化实体构造器
			builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); // 设置浏览器兼容模式

			builder.addPart("file", new FileBody(file)); // 添加"file"字段及其值；此处注意字段名称必须是"file"
			builder.addPart("key", new StringBody(key, ContentType.create("text/plain", Consts.UTF_8))); // 添加"key"字段及其值
			builder.addPart("secret", new StringBody(secret, ContentType.create("text/plain", Consts.UTF_8))); // 添加"secret"字段及其值
			builder.addPart("typeId", new StringBody(typeId, ContentType.create("text/plain", Consts.UTF_8))); // 添加"typeId"字段及其值
			builder.addPart("format", new StringBody(format, ContentType.create("text/plain", Consts.UTF_8))); // 添加"format"字段及其值

			HttpEntity reqEntity = builder.setCharset(CharsetUtils.get("UTF-8")).build(); // 设置请求的编码格式，并构造实体

			post.setEntity(reqEntity);
			// **************************************</向post方法中封装实体>************************************

			HttpResponse response = client.execute(post); // 4.执行post方法，返回HttpResponse的对象
			if (response.getStatusLine().getStatusCode() == 200) { // 5.如果返回结果状态码为200，则读取响应实体response对象的实体内容，并封装成String对象返回
				result = EntityUtils.toString(response.getEntity(), "UTF-8");
				Message mes = new Message();
				mes.obj = result;
				mes.what = 2;
				handler.sendMessage(mes);
			} else {
				//System.out.println("服务器返回异常");
				//Toast.makeText(getApplicationContext(), "服务器返回异常", Toast.LENGTH_SHORT).show();
				Message mes = new Message();
				mes.obj = "服务器返回异常";
				mes.what = 1;
				handler.sendMessage(mes);
			}

			try {
				HttpEntity e = response.getEntity(); // 6.关闭资源
				if (e != null) {
					InputStream instream = e.getContent();
					instream.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				((InputStream) response).close();
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
		}
		//System.out.println("result:"+result);
		return result; // 7.返回识别结果

	}
	
	/**生成拍照后图片的中间矩形的宽度和高度
	 * @param w 屏幕上的矩形宽度，单位px
	 * @param h 屏幕上的矩形高度，单位px
	 * @return
	 */
	private Point createCenterPictureRect(int w, int h){
		
		int wScreen = DisplayUtil.getScreenMetrics(this).x;
		int hScreen = DisplayUtil.getScreenMetrics(this).y;
		int wSavePicture = CameraInterface.getInstance().doGetPrictureSize().y; //因为图片旋转了，所以此处宽高换位
		int hSavePicture = CameraInterface.getInstance().doGetPrictureSize().x; //因为图片旋转了，所以此处宽高换位
		float wRate = (float)(wSavePicture) / (float)(wScreen);
		float hRate = (float)(hSavePicture) / (float)(hScreen);
		float rate = (wRate <= hRate) ? wRate : hRate;//也可以按照最小比率计算
		
		int wRectPicture = (int)( w * wRate);
		int hRectPicture = (int)( h * hRate);
		return new Point(wRectPicture, hRectPicture);
		
	}
	/**
	 * 生成屏幕中间的矩形
	 * @param w 目标矩形的宽度,单位px
	 * @param h	目标矩形的高度,单位px
	 * @return
	 */
	private Rect createCenterScreenRect(int w, int h){
		int x1 = DisplayUtil.getScreenMetrics(this).x / 2 - w / 2;
		int y1 = DisplayUtil.getScreenMetrics(this).y / 2 - h / 2;
		int x2 = x1 + w;
		int y2 = y1 + h;
		return new Rect(x1, y1, x2, y2);
	}
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();

	}

	@Override
	public int getLayout() {
		// TODO Auto-generated method stub
		return R.layout.activity_camera;
	}

	@Override
	public void OnActCreate(Bundle savedInstanceState) {
		Thread openThread = new Thread(){
			@Override
			public void run() {
				// TODO Auto-generated method stub
				CameraInterface.getInstance().doOpenCamera(CameraActivity.this);
			}
		};
		openThread.start();
		initUI();
		initViewParams();
		
		shutterBtn.setOnClickListener(new BtnListeners());
		
		registerReceiver(new CardCast(), new IntentFilter("camelDone"));
	}

	@Override
	public void OnViewClick(View v) {
		// TODO Auto-generated method stub
		
	}
}
